package index.metadata;

import static storage.file.Page.BLOCK_SIZE;
import static storage.sql.Types.*;
import index.Index;
import index.btree.BTreeIndex;
import server.starDB;
import storage.metadata.StatInfo;
import storage.record.Schema;
import storage.record.TableInfo;
import storage.tx.Transaction;

public class IndexInfo {
	private String fldname;
	private int idxnum;
	private Transaction tx;
	private TableInfo ti;
	private StatInfo si;
	
	public IndexInfo(String tblname, String fldname, int idnum, Transaction tx){
		this.fldname = fldname;
		this.idxnum = idxnum;
		this.tx = tx;
		ti = starDB.mdMgr().getTableInfo(tblname, tx);
		si = starDB.mdMgr().getStatInfo(tblname, ti, tx);
	}
	
	public Index open(){
		Schema sch = schema();
		return new BTreeIndex(idxnum, sch, tx);
	}
	
	public int blocksAccessed(){
		int rpb = BLOCK_SIZE / ti.recordLength();
		int numblocks = si.recordsOutput() / rpb;
		return BTreeIndex.searchCost(numblocks, rpb);
	}
	
	public int recordsOutput(){
		return si.recordsOutput() / si.distinctValues(fldname);
	}
	
	private Schema schema(){
		Schema sch = new Schema();
		sch.addIntField("block");
		sch.addIntField("id");
		if (ti.schema().type(fldname) == INTEGER)
			sch.addIntField("dataval");
		else{
			int fldlen = ti.schema().length(fldname);
			sch.addStringField("dataval", fldlen);
		}
		return sch;
	}

}
